const app = getApp();

Page({
    data: {
        isOnline: false,
        isLoggedIn: false,
        currentDate: '',
        menuList: [
            {text: '消息中心', icon: '💬', badge: 0},
            {text: '帮助与客服', icon: '👨‍💼'},
            {text: '设置', icon: '⚙️'}
        ],
        unreadMessageCount: 0, // 未读消息数量
        logoutItem: {text: '退出登录', icon: '🚪'},
        riderlist: {
            id: null,
            name: null,
            phone: null,
            avatar: null,
            vehicleType: null,
            vehicleTypeName: null,
            vehiclePlate: null,
            status: null,
            statusName: null,
            createTime: null,
            updateTime: null
        },
        walletInfo: {
            balance: 0,           // 钱包余额（真实余额）
            todayIncome: 0,       // 今日收入
            completedOrders: 0,   // 完成订单数
            bonusAmount: 0        // 奖励金额
        },
        refreshTimer: null,     // 钱包刷新定时器
        sendOrdersTimer: null   // 自动派单定时器
    },

    onLoad() {
        this.setCurrentDate();
        this.checkLoginStatus();
        if (this.data.isLoggedIn) {
            this.fetchRiderInfo();
            this.fetchWalletInfo();
        }
    },

    onShow() {
        this.setCurrentDate();
        this.checkLoginStatus();
        if (this.data.isLoggedIn) {
            this.fetchWalletInfo(); // 每次显示页面时刷新钱包数据
            this.fetchUnreadMessageCount(); // 获取未读消息数量
            this.startAutoRefresh(); // 开始自动刷新
        }
    },

    onHide() {
        this.stopAutoRefresh(); // 页面隐藏时停止自动刷新
        // 注意：不停止自动派单，因为需要在后台继续运行
    },

    onUnload() {
        this.stopAutoRefresh(); // 页面卸载时停止自动刷新
        this.stopSendOrdersTimer(); // 页面卸载时停止自动派单
    },

    // 设置当前日期
    setCurrentDate() {
        const now = new Date();
        const month = now.getMonth() + 1;
        const day = now.getDate();
        this.setData({
            currentDate: `${month}月${day}日`
        });
    },

    // 检查登录状态
    checkLoginStatus() {
        const token = app.globalData.ridertoken;
        const riderId = app.globalData.riderId;

        const isLoggedIn = !!(token && riderId);
        this.setData({isLoggedIn});

        if (!isLoggedIn) {
            // 未登录时清空数据
            this.setData({
                riderlist: {
                    id: null,
                    name: null,
                    phone: null,
                    avatar: null,
                    vehicleType: null,
                    vehicleTypeName: null,
                    vehiclePlate: null,
                    status: null,
                    statusName: null,
                    createTime: null,
                    updateTime: null
                },
                walletInfo: {
                    balance: 0,
                    todayIncome: 0,
                    completedOrders: 0,
                    bonusAmount: 0
                },
                isOnline: false
            });
        }
    },

    // 跳转到登录页面
    goToLogin() {
        wx.navigateTo({
            url: '/pages/logs/logs'
        });
    },

    fetchRiderInfo() {
        const ip = app.globalData.userIPInfo;
        const token = app.globalData.ridertoken;
        const riderId = app.globalData.riderId; // 你可以从缓存或者其他地方动态获取

        if (!token) {
            wx.showToast({title: '未登录，请先登录', icon: 'none'});
            return;
        }

        wx.request({
            url: `${ip}/api/riders/info?id=` + riderId,
            method: 'GET',
            header: {
                'Authorization': 'Bearer ' + token,
                'content-type': 'application/json'
            },
            success: (res) => {
                if (res.data.code === 200) {
                    const data = res.data.data;

                    // 保存骑手信息到本地存储，供修改密码时使用
                    wx.setStorageSync('riderName', data.name);
                    wx.setStorageSync('riderPhone', data.phone);
                    wx.setStorageSync('riderVehicleType', data.vehicleType);
                    wx.setStorageSync('riderVehiclePlate', data.vehiclePlate);
                    wx.setStorageSync('riderStatus', data.status);

                    this.setData({
                        riderlist: {
                            id: data.id,
                            name: data.name,
                            phone: data.phone,
                            avatar: data.avatar || '/assets/icons/default_avatar.png',
                            vehicleType: data.vehicleType,
                            vehicleTypeName: data.vehicleTypeName,
                            vehiclePlate: data.vehiclePlate,
                            status: data.status,
                            statusName: data.statusName,
                            createTime: data.createTime,
                            updateTime: data.updateTime
                        },
                        isLoggedIn: true,
                        isOnline: data.status === 1 // 1表示空闲状态，可以接单
                    });

                    // 如果当前是在线状态，开始自动派单
                    if (data.status === 1) {
                        this.startSendOrdersTimer();
                    }
                } else {
                    wx.showToast({title: res.data.message || '获取骑手信息失败', icon: 'none'});
                }
            },
            fail: () => {
                wx.showToast({title: '请求失败', icon: 'none'});
            }
        });
    },

    // 开始自动刷新
    startAutoRefresh() {
        // 清除之前的定时器
        this.stopAutoRefresh();

        // 设置30秒刷新一次
        this.setData({
            refreshTimer: setInterval(() => {
                this.fetchWalletInfo();
                this.fetchUnreadMessageCount();
            }, 30000) // 30秒 = 30000毫秒
        });
    },

    // 停止自动刷新
    stopAutoRefresh() {
        if (this.data.refreshTimer) {
            clearInterval(this.data.refreshTimer);
            this.setData({
                refreshTimer: null
            });
        }
    },

    // 开始自动派单
    startSendOrdersTimer() {
        // 清除之前的定时器
        this.stopSendOrdersTimer();

        // 设置30秒执行一次
        this.setData({
            sendOrdersTimer: setInterval(() => {
                this.callSendOrdersAPI();
            }, 30000) // 30秒 = 30000毫秒
        });
    },

    // 停止自动派单
    stopSendOrdersTimer() {
        if (this.data.sendOrdersTimer) {
            clearInterval(this.data.sendOrdersTimer);
            this.setData({
                sendOrdersTimer: null
            });
        }
    },

    // 调用智能派单API
    callSendOrdersAPI() {
        const ip = app.globalData.userIPInfo;
        const token = app.globalData.ridertoken;

        if (!token) {
            this.stopSendOrdersTimer();
            return;
        }

        // 获取骑手当前位置
        this.getCurrentRiderLocation((location) => {
            if (!location) {
                // 位置获取失败，跳过本次派单
                return;
            }

            // 格式化位置信息为 "lat,lng" 格式
            const riderLocationStr = `${location.latitude},${location.longitude}`;

            wx.request({
                url: `${ip}/api/orders/rider/smartSendOrders`,
                method: 'POST',
                header: {
                    'Authorization': 'Bearer ' + token,
                    'Content-Type': 'application/json'
                },
                data: [riderLocationStr], // 传递位置信息数组
                success: (res) => {
                    // 静默处理智能派单结果
                    if (res.data && res.data.code === 200) {
                        console.log('智能派单成功:', res.data.message);
                    }
                },
                fail: (error) => {
                    // 静默处理智能派单错误
                    console.error('智能派单失败:', error);
                }
            });
        });
    },

    // 获取骑手当前位置
    getCurrentRiderLocation(callback) {
        // 先检查本地存储是否有位置信息（5分钟内有效）
        const storedLocation = wx.getStorageSync('riderLocation');
        if (storedLocation && storedLocation.timestamp) {
            const now = Date.now();
            const fiveMinutes = 5 * 60 * 1000; // 5分钟
            if (now - storedLocation.timestamp < fiveMinutes) {
                if (callback) callback(storedLocation);
                return;
            }
        }

        // 先检查授权状态
        wx.getSetting({
            success: (res) => {
                if (res.authSetting['scope.userLocation']) {
                    // 已授权，直接获取位置
                    this.getRiderLocationDirect(callback);
                } else {
                    // 未授权，静默失败（不弹窗打扰用户）
                    if (callback) callback(null);
                }
            },
            fail: () => {
                if (callback) callback(null);
            }
        });
    },

    // 直接获取骑手位置
    getRiderLocationDirect(callback) {
        wx.getLocation({
            type: 'gcj02',
            isHighAccuracy: true,
            success: (res) => {
                const location = {
                    latitude: res.latitude,
                    longitude: res.longitude,
                    timestamp: Date.now()
                };

                // 存储到本地（5分钟有效期）
                wx.setStorageSync('riderLocation', location);

                if (callback) callback(location);
            },
            fail: (error) => {
                // 静默处理位置获取失败
                if (callback) callback(null);
            }
        });
    },

    // 获取未读消息数量
    fetchUnreadMessageCount() {
        const ip = app.globalData.userIPInfo;
        const token = app.globalData.ridertoken;
        const riderId = app.globalData.riderId;

        if (!token || !riderId) {
            this.updateMessageBadge(0);
            return;
        }

        let totalUnreadCount = 0;

        // 获取新订单数量（待接单）
        wx.request({
            url: `${ip}/api/orders/listNoOrdersReceived`,
            method: 'GET',
            header: {
                'Authorization': 'Bearer ' + token
            },
            success: (res) => {
                if (res.data.code === 200) {
                    const allOrders = res.data.data || [];
                    const newOrders = allOrders.filter(item =>
                        item.orderStatusName === '待接单' || item.orderStatus === 1
                    ).length;
                    totalUnreadCount += newOrders;
                    this.checkOtherUnreadMessages(totalUnreadCount);
                } else {
                    this.updateMessageBadge(0);
                }
            },
            fail: () => {
                this.updateMessageBadge(0);
            }
        });
    },

    // 检查其他未读消息
    checkOtherUnreadMessages(currentCount) {
        const ip = app.globalData.userIPInfo;
        const token = app.globalData.ridertoken;
        const riderId = app.globalData.riderId;

        // 获取待取货订单数量
        wx.request({
            url: `${ip}/api/orders/rider/list?riderId=${riderId}&orderStatus=2`,
            method: 'GET',
            header: {
                'Authorization': 'Bearer ' + token
            },
            success: (res) => {
                if (res.data.code === 200) {
                    const pickupOrders = (res.data.data || []).length;
                    currentCount += pickupOrders;
                }
                this.checkDeliveryMessages(currentCount);
            },
            fail: () => {
                this.updateMessageBadge(currentCount);
            }
        });
    },

    // 检查配送中消息
    checkDeliveryMessages(currentCount) {
        const ip = app.globalData.userIPInfo;
        const token = app.globalData.ridertoken;
        const riderId = app.globalData.riderId;

        // 获取配送中订单数量
        wx.request({
            url: `${ip}/api/orders/rider/list?riderId=${riderId}&orderStatus=3`,
            method: 'GET',
            header: {
                'Authorization': 'Bearer ' + token
            },
            success: (res) => {
                if (res.data.code === 200) {
                    const deliveryOrders = (res.data.data || []).length;
                    currentCount += deliveryOrders;
                }
                this.checkDeliveryReadyMessages(currentCount);
            },
            fail: () => {
                this.updateMessageBadge(currentCount);
            }
        });
    },

    // 检查待收货消息
    checkDeliveryReadyMessages(currentCount) {
        const ip = app.globalData.userIPInfo;
        const token = app.globalData.ridertoken;
        const riderId = app.globalData.riderId;

        // 获取待收货订单数量
        wx.request({
            url: `${ip}/api/orders/rider/list?riderId=${riderId}&orderStatus=4`,
            method: 'GET',
            header: {
                'Authorization': 'Bearer ' + token
            },
            success: (res) => {
                if (res.data.code === 200) {
                    const deliveryReadyOrders = (res.data.data || []).length;
                    currentCount += deliveryReadyOrders;
                }
                this.updateMessageBadge(currentCount);
            },
            fail: () => {
                this.updateMessageBadge(currentCount);
            }
        });
    },

    // 更新消息徽章
    updateMessageBadge(count) {

        const menuList = this.data.menuList.map(item => {
            if (item.text === '消息中心') {
                return {
                    ...item,
                    badge: count > 0 ? count : 0
                };
            }
            return item;
        });

        this.setData({
            menuList,
            unreadMessageCount: count
        });
    },

    // 获取钱包信息
    fetchWalletInfo() {
        const ip = app.globalData.userIPInfo;
        const token = app.globalData.ridertoken;
        const riderId = app.globalData.riderId;

        if (!token || !riderId) {
            return; // 未登录时不获取钱包数据
        }

        // 获取已完成订单 (orderStatus=5表示已完成)
        wx.request({
            url: `${ip}/api/orders/rider/list?riderId=${riderId}&orderStatus=5`,
            method: 'GET',
            header: {
                'Authorization': 'Bearer ' + token
            },
            success: (res) => {
                if (res.data.code === 200) {
                    const allCompletedOrders = res.data.data || [];

                    // 筛选今日完成的订单
                    const today = new Date();
                    const todayStr = today.toISOString().split('T')[0]; // YYYY-MM-DD格式

                    const todayOrders = allCompletedOrders.filter(order => {
                        if (!order.updateTime) return false;
                        const orderDate = new Date(order.updateTime).toISOString().split('T')[0];
                        return orderDate === todayStr;
                    });

                    // 计算今日收入
                    const todayIncome = todayOrders.reduce((sum, order) => {
                        return sum + (parseFloat(order.deliveryFee) || 0);
                    }, 0);

                    // 完成订单数
                    const completedOrders = todayOrders.length;

                    // 获取骑手奖励金额和钱包余额
                    this.fetchRiderBonus(riderId, todayIncome, completedOrders);
                    this.fetchWalletBalance(riderId, todayIncome, completedOrders);
                }
            },
            fail: () => {
                // 静默处理错误
            }
        });
    },

    // 获取骑手奖励金额 - 单次调用，通过定时器30秒刷新
    fetchRiderBonus(riderId, todayIncome, completedOrders) {
        const ip = app.globalData.userIPInfo;
        const token = app.globalData.ridertoken;

        // 使用当前月份字符串格式：xxxx-xx月
        const now = new Date();
        const currentMonth = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}月`;

        wx.request({
            url: `${ip}/api/platform/settlement/calculateRiderBonusByMonth?riderId=${riderId}&month=${currentMonth}`,
            method: 'GET',
            header: {
                'Authorization': 'Bearer ' + token
            },
            success: (res) => {
                if (res.data.code === 200) {
                    const bonusAmount = parseFloat(res.data.data) || 0;

                    this.setData({
                        'walletInfo.bonusAmount': bonusAmount.toFixed(2),
                        'walletInfo.todayIncome': todayIncome.toFixed(2),
                        'walletInfo.completedOrders': completedOrders
                    });
                } else {
                    // 如果获取奖励失败，使用默认值
                    this.setData({
                        'walletInfo.bonusAmount': '0.00',
                        'walletInfo.todayIncome': todayIncome.toFixed(2),
                        'walletInfo.completedOrders': completedOrders
                    });
                }
            },
            fail: (err) => {
                // 失败时使用默认值
                this.setData({
                    'walletInfo.bonusAmount': '0.00',
                    'walletInfo.todayIncome': todayIncome.toFixed(2),
                    'walletInfo.completedOrders': completedOrders
                });
            }
        });
    },

    // 获取钱包余额（真实余额）
    fetchWalletBalance(riderId, todayIncome, completedOrders) {
        const ip = app.globalData.userIPInfo;
        const token = app.globalData.ridertoken;

        // 这里应该调用真实的钱包余额API
        // 目前使用模拟数据，您可以替换为真实的API接口

        // 模拟API调用
        wx.request({
            url: `${ip}/api/riders/info?id=${riderId}`, // 假设的钱包余额API
            method: 'GET',
            header: {
                'Authorization': 'Bearer ' + token
            },
            success: (res) => {
                if (res.data.code === 200) {
                    const balance = parseFloat(res.data.data.money) || 0;
                    this.setData({
                        'walletInfo.balance': balance.toFixed(2)
                    });
                } else {
                    // API失败时，使用累计收入的80%作为可提现余额
                    const totalIncome = parseFloat(this.data.walletInfo.bonusAmount) || 0;
                    const estimatedBalance = totalIncome * 0.8;
                    this.setData({
                        'walletInfo.balance': estimatedBalance.toFixed(2)
                    });
                }
            },
            fail: () => {
                // 网络失败时，使用奖励金额的80%作为可提现余额
                const bonusAmount = parseFloat(this.data.walletInfo.bonusAmount) || 0;
                const estimatedBalance = bonusAmount * 0.8;
                this.setData({
                    'walletInfo.balance': estimatedBalance.toFixed(2)
                });
            }
        });
    },

    // 提现功能 - 跳转到提现页面
    onWithdraw() {
        const balance = parseFloat(this.data.walletInfo.balance);

        if (balance <= 0) {
            wx.showToast({
                title: '余额不足',
                icon: 'none'
            });
            return;
        }

        // 跳转到提现页面
        wx.navigateTo({
            url: '/pages/withdraw/index'
        });
    },


    // 查看收入明细
    onViewIncomeDetail() {
        wx.navigateTo({
            url: '/pages/income-detail/index'
        });
    },

    // 查看提现记录
    onViewWithdrawHistory() {
        wx.navigateTo({
            url: '/pages/withdraw-history/index'
        });
    },

    toggleOnline(e) {
        const isOnline = e.detail.value;
        const ip = app.globalData.userIPInfo;
        const token = app.globalData.ridertoken;
        const riderId = app.globalData.riderId;
        const status = isOnline ? 1 : 2;

        this.setData({isOnline});

        wx.request({
            url: `${ip}/api/riders/status`,
            method: 'POST',
            data: {
                id: riderId,
                status
            },
            header: {
                'content-type': 'application/x-www-form-urlencoded',
                'Authorization': 'Bearer ' + token
            },
            success: (res) => {
                if (res.statusCode === 200 && res.data.code === 200) {
                    wx.showToast({
                        title: isOnline ? '已上线' : '已下线',
                        icon: 'success'
                    });

                    // 根据状态控制自动派单
                    if (isOnline) {
                        this.startSendOrdersTimer(); // 上线时开始自动派单
                    } else {
                        this.stopSendOrdersTimer(); // 下线时停止自动派单
                    }
                } else {
                    wx.showToast({title: '状态更新失败', icon: 'none'});
                    this.setData({isOnline: !isOnline});
                }
            },
            fail: () => {
                wx.showToast({title: '网络错误', icon: 'none'});
                this.setData({isOnline: !isOnline});
            }
        });
    },

    onMenuTap(e) {
        const item = e.currentTarget.dataset.item;
        const menuText = item.text;

        switch (menuText) {
            case '设置':
                wx.navigateTo({
                    url: '/pages/change-password/index'
                });
                break;
            case '消息中心':
                wx.switchTab({
                    url: '/pages/message/index'
                });
                break;
            case '帮助与客服':
                if (this.data.isLoggedIn) {
                    wx.navigateTo({
                        url: '/pages/customer-service/index'
                    });
                } else {
                    wx.showToast({
                        title: '请先登录',
                        icon: 'none'
                    });
                }
                break;
            case '退出登录':
                this.showLogoutConfirm();
                break;
            default:
                wx.showToast({title: `${menuText}功能开发中`, icon: 'none'});
                break;
        }
    },

    // 显示退出登录确认对话框
    showLogoutConfirm() {
        wx.showModal({
            title: '退出登录',
            content: '确定要退出登录吗？',
            confirmText: '确定',
            cancelText: '取消',
            success: (res) => {
                if (res.confirm) {
                    this.logout();
                }
            }
        });
    },

    // 退出登录
    logout() {
        const ip = app.globalData.userIPInfo;
        const token = app.globalData.ridertoken;
        const riderId = app.globalData.riderId;

        // 先停止所有定时器
        this.stopAutoRefresh();
        this.stopSendOrdersTimer();

        // 设置骑手状态为2（退出登录状态）
        if (token && riderId) {
            wx.request({
                url: `${ip}/api/riders/status`,
                method: 'POST',
                data: {
                    id: riderId,
                    status: 2 // 设置状态为2
                },
                header: {
                    'content-type': 'application/x-www-form-urlencoded',
                    'Authorization': 'Bearer ' + token
                },
                success: (res) => {
                    // 静默处理设置状态结果
                },
                fail: (error) => {
                    // 静默处理设置状态错误
                },
                complete: () => {
                    // 无论成功失败都执行登出操作
                    this.performLogout();
                }
            });
        } else {
            this.performLogout();
        }
    },

    // 执行登出操作
    performLogout() {
        // 清除本地存储的登录信息
        wx.removeStorageSync('ridertoken');
        wx.removeStorageSync('riderId');
        wx.removeStorageSync('riderName');
        wx.removeStorageSync('riderPhone');
        wx.removeStorageSync('riderVehicleType');
        wx.removeStorageSync('riderVehiclePlate');
        wx.removeStorageSync('riderStatus');

        // 清除全局数据
        app.globalData.ridertoken = null;
        app.globalData.riderId = null;

        // 重置页面数据
        this.setData({
            isLoggedIn: false,
            isOnline: false,
            riderlist: {
                id: null,
                name: null,
                phone: null,
                avatar: null,
                vehicleType: null,
                vehicleTypeName: null,
                vehiclePlate: null,
                status: null,
                statusName: null,
                createTime: null,
                updateTime: null
            },
            walletInfo: {
                balance: 0,
                todayIncome: 0,
                completedOrders: 0,
                bonusAmount: 0
            }
        });

        wx.showToast({
            title: '已退出登录',
            icon: 'success'
        });

        // 跳转到登录页面
        setTimeout(() => {
            wx.navigateTo({
                url: '/pages/logs/logs'
            });
        }, 1500);
    },

    // 点击顶部资料卡跳转
    onProfileTap() {
        if (this.data.isLoggedIn) {
            wx.navigateTo({
                url: '/pages/rider-info/index'
            });
        } else {
            wx.navigateTo({
                url: '/pages/logs/logs'
            });
        }
    },

    // 显示退出登录确认对话框
    showLogoutConfirm() {
        wx.showModal({
            title: '退出登录',
            content: '确定要退出登录吗？',
            confirmText: '确定',
            cancelText: '取消',
            success: (res) => {
                if (res.confirm) {
                    this.logout();
                }
            }
        });
    },

    // 退出登录
    logout() {
        const ip = app.globalData.userIPInfo;
        const token = app.globalData.ridertoken;
        const riderId = app.globalData.riderId;

        // 先停止所有定时器
        this.stopAutoRefresh();
        this.stopSendOrdersTimer();

        // 设置骑手状态为2（退出登录状态）
        if (token && riderId) {
            wx.request({
                url: `${ip}/api/riders/status`,
                method: 'POST',
                data: {
                    id: riderId,
                    status: 2 // 设置状态为2
                },
                header: {
                    'content-type': 'application/x-www-form-urlencoded',
                    'Authorization': 'Bearer ' + token
                },
                success: (res) => {
                    // 静默处理设置状态结果
                },
                fail: (error) => {
                    // 静默处理设置状态错误
                },
                complete: () => {
                    // 无论成功失败都执行登出操作
                    this.performLogout();
                }
            });
        } else {
            this.performLogout();
        }
    },

    // 执行登出操作
    performLogout() {
        // 清除本地存储的登录信息
        wx.removeStorageSync('ridertoken');
        wx.removeStorageSync('riderId');
        wx.removeStorageSync('riderName');
        wx.removeStorageSync('riderPhone');
        wx.removeStorageSync('riderVehicleType');
        wx.removeStorageSync('riderVehiclePlate');
        wx.removeStorageSync('riderStatus');

        // 清除全局数据
        app.globalData.ridertoken = null;
        app.globalData.riderId = null;

        // 重置页面数据
        this.setData({
            isLoggedIn: false,
            isOnline: false,
            riderlist: {
                id: null,
                name: null,
                phone: null,
                avatar: null,
                vehicleType: null,
                vehicleTypeName: null,
                vehiclePlate: null,
                status: null,
                statusName: null,
                createTime: null,
                updateTime: null
            },
            walletInfo: {
                balance: 0,
                todayIncome: 0,
                completedOrders: 0,
                bonusAmount: 0
            }
        });

        wx.showToast({
            title: '已退出登录',
            icon: 'success'
        });

        // 跳转到登录页面
        setTimeout(() => {
            wx.navigateTo({
                url: '/pages/logs/logs'
            });
        }, 1500);
    },
});
